/*
 * Proxy.h
 *
 *  Created on: Dec 24, 2011
 *      Author: quotrader
 */

#ifndef PROXY_H_
#define PROXY_H_

#include "Scheduler.h"
#include <time.h>
#include <sys/trace.h>
#include <sys/neutrino.h>

class Proxy: public Scheduler {
public:
	Proxy();
	void execute();
	int test;

	static void *control(void *object) {

		// check the received object is a correct one
		Proxy *ci = ((Proxy *) object);
		if (!ci) return NULL;

		// definitions an initializations
		int chid 				= ci->setupPuls();
		bool exitFlag			=true;
		Task *currentTask 		= NULL;
		struct _pulse pulse;
		timespec t;
		int value=0;
		int newParam;
		int highestPrioTskId;


		// catching-pulses loop
		do{
			// receive pulses
			exitFlag=true;
			MsgReceive(chid, &pulse, sizeof(pulse), NULL);

			// ask task manager if any task got changed
			if (ci->tMng->changed) {

				//reassign priorities
				highestPrioTskId= ci->algr->rePrioritize(ci->tMng,ci->startPriority,ci->priorityIncr);

				// finding current task
				for (int i = 0; i < ci->tMng->numTask && !ci->tMng->tasks[i].done; i++)
					if (ci->tMng->tasks[i].running) currentTask = &ci->tMng->tasks[i];

				if (currentTask != NULL && currentTask->id != highestPrioTskId){
					currentTask->stopFlag = true;
				}
			}

			// check if all tasks got finished to exit the loop
			for (int i = 0; i < ci->tMng->numTask; i++)
				if (!ci->tMng->tasks[i].done) exitFlag = false;

			// let one of the task work
			sem_getvalue(&ci->semId,&value);
			if(value<1) if(sem_post(&ci->semId)==-1)cout<<"problem to wait in control";

		}while(!exitFlag);

		return NULL;
	}
};

#endif /* PROXY_H_ */
